import { GetterTree, ActionTree, MutationTree } from 'vuex'
interface State {
    token: string;
    userInfo: null | object;
}

export const state = function () {
    return {
        token: '',
        userInfo: null,
    } as State
}

export type RootState = ReturnType<typeof state>

export const getters: GetterTree<RootState, RootState> = {
//   name: state => state.name,
}

export const mutations: MutationTree<RootState> = {
  SET_STATE(state, newState: State) {
    for (const key in newState) {
        if (Object.prototype.hasOwnProperty.call(newState, key)) {
            // @ts-ignore
            state[key] = newState[key]
        }
    }
    // @ts-ignore
    this.$cookies.set('_store', state)
 },
  // 设置token
  SET_TOKEN(state, token: State['token']) {
    state.token = token
    // @ts-ignore
    this.$cookies.set('_store', state)
    
 },

 // 设置userInfo
 SET_USERINFO(state, userInfo: State['userInfo']) {
    state.userInfo = userInfo
    // @ts-ignore
    this.$cookies.set('_store', state)
 },
}

export const actions: ActionTree<RootState, RootState> = {
    nuxtServerInit (_store, _context) {
        console.log('nuxtServerInit执行====', _context.$cookies.get('_store'))
        if (_context.store) {
            _context.store.commit('SET_STATE', _context.$cookies.get('_store') || {})
            // 设置store/app模块内容
            _context.store.commit('app/SET_STATE', _context.$cookies.get('_store/app') || {})
             // 设置store/app模块内容
             _context.store.commit('admin/SET_STATE', _context.$cookies.get('_store/admin') || {})
        }
        
    }
}